<!--
 * @Author: your name
 * @Date: 2021-10-06 21:55:32
 * @LastEditTime: 2021-10-07 17:27:18
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \common-vue\src\components\mForm\MyFormItem.vue
-->
<template>
  <div class="MyFormItem-box">
    <!-- 表单前面文字说明 -->
    <label v-if="label">{{ label }}</label>
    <!-- 通过插槽形式来引入未来的input/textArea等一系列表单元素 -->
    <slot></slot>
    <!-- 错误提示 -->
    <p class="error-box" v-if="error">{{ error }}</p>
  </div>
</template>

<script>
import Validator from 'async-validator'

export default {
  name: 'MyFormItem',
  // 拿顶层父亲中数据(rules和model)为校验所用
  inject: ['form'],
  props: {
    label: {
      type: String,
      default: ''
    },
    prop: {
      type: String
    }
  },
  data() {
    return {
      error: ''
    }
  },
  mounted() {
    // 对MyInput组件中validate事件的监听
    this.$on('validate', () => {
      const result = this.validate()
      console.log('result', result)
    })
  },
  methods: {
    // 进行校验逻辑
    validate() {
      const rule = this.form.rules[this.prop]
      const value = this.form.model[this.prop]
      // async-validator
      const validator = new Validator({
        [this.prop]: rule
      })
      // 这里返回的就是一个Promise
      return validator.validate({
        [this.prop]: value
      }, errors => {
        if (errors) {
          this.error = errors[0].message
        } else {
          this.error = ''
        }
      })
    }
  }
}
</script>

<style scoped lang="less">
.error-box{
  color: red;
}
</style>
